package com.hjrpc.babyyamall.product.web;

import com.hjrpc.babyyamall.product.entity.CategoryEntity;
import com.hjrpc.babyyamall.product.feign.MemberFeignService;
import com.hjrpc.babyyamall.product.service.CategoryService;
import com.hjrpc.babyyamall.product.vo.Catalog2Vo;
import com.hjrpc.common.constant.AuthServerConstant;
import com.hjrpc.common.dto.LoginUserTo;
import com.hjrpc.common.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

@Controller
public class FirstPageController {
    @Autowired
    CategoryService categoryService;
    @Autowired
    MemberFeignService memberFeignService;
    @Autowired
    StringRedisTemplate redisTemplate;

    @RequestMapping({"/", "/index", "/index.html"})
    public String getIndex(Model model, @RequestParam(value = "ssoToken", required = false) String ssoToken, HttpServletResponse response) {
        //获取所有的一级分类
        List<CategoryEntity> catagories = categoryService.getLevel1Catagories();
        if (ssoToken != null) {
            Long memberId = Long.valueOf(redisTemplate.opsForValue().get(AuthServerConstant.AUTH_SSO_TOKEN_PREFIX + ssoToken));
            R r = memberFeignService.info(memberId);
            if (r.isSuccess()) {
                LoginUserTo loginUser = r.getData(LoginUserTo.class);
                model.addAttribute("loginUser", loginUser);
                model.addAttribute("ssoToken", ssoToken);
                Cookie cookie = new Cookie("ssoToken", ssoToken);
                response.addCookie(cookie);
            }
        }
        model.addAttribute("catagories", catagories);
        return "index";
    }

    @GetMapping("index/catalog.json")
    @ResponseBody
    public Map<String, List<Catalog2Vo>> getCategoryMap() {
        return categoryService.getCatalogMap();
    }
}
